<?php

require_once ROOT_DIR.'models/Todo.php';
require_once ROOT_DIR.'controls/RightHelper.php';

/**
 * Tries to update the todo and echos the resulting view.
 * @param int $id
 * @param string $title
 * @param string $description
 * @param timestamp $targetDate
 * @param float $projectedHours
 * @param string $status oS(on schedule), bS(behind schedule), n(new) or w(waiting)
 */
function editTodo($id, $title, $description, $targetDate, $projectedHours, $status){
	$todo = Todo::getTodo($id);
	if(!is_null($todo)){
		if($todo->getCreatorID() == $_SESSION['USER_ID'] || $_SESSION['USER_NAME'] == 'admin' || RightHelper::checkIfResponsible($todo)){
			if(!is_null($title)){
				$todo->setTitle($title);
			}
			
			if(!is_null($description)){
				$todo->setDescription($description);
			}
			
			if(!is_null($targetDate)){
				$todo->setTargetDate($targetDate);
			}
			
			if(!is_null($projectedHours)){
				$todo->setProjectedHours($projectedHours);
			}
			
			if(!is_null($status)){
				switch($status){
					case 'n': $status = 'n'; break;
					case 'w': $status = 'w'; break;
					case 'bS': $status = 'bS'; break;
					case 'oS': $status = 'oS'; break;
					case 'c': $status = 'c'; break;
					default: $status = 'oS'; break;
				}
				$todo->setStatus($status);
			}
			
			if($todo->saveToDB()){
				$res = new ResultJSON(false, session_id());
				$res->addItem('tID', $todo->getID());
				echo $res->renderView();
			} else {
				$res = new ResultJSON(true, session_id(), ERROR_ACTION_FAILED);
				echo $res->renderView();
			}
		} else {
			$res = new ResultJSON(true, session_id(), ERROR_NOT_ALLOWED);
			echo $res->renderView();
		}
	} else {
		$res = new ResultJSON(true, session_id(), ERROR_TODO_DOES_NOT_EXIST);
		echo $res->renderView();
	}
}

?>